package com.project.core.util;

import java.util.Objects;

/**
 * @author mengxj
 * @date 2022/6/1 10:24
 */
public class JcaUtil {

    /**
     * 算法名称AES
     */
    protected static final String AES = "AES";

    /**
     * 将二进制数组转换成16进制字符串
     * @param bytes 二进制数组
     * @return 16进制字符串
     */
    protected static String bytesToStr(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制字符串解析成原二进制数组，也就是加密后的数组
     * @param hexStr 16进制字符串
     * @return 原二进制数组
     */
    protected static byte[] strToBytes(String hexStr) {
        int arrLen = hexStr.length() / 2;
        byte[] result = new byte[arrLen];
        for (int i = 0;i < arrLen; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low =  Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 校验参数
     * @param obj 参数
     * @param msg 异常提示语
     */
    protected static void checkParam(Object obj, String msg){
        if(Objects.isNull(obj)){
            throw new NullPointerException(msg);
        }
        if(obj instanceof String && "".equals(obj.toString().trim())){
            throw new NullPointerException(msg);
        }
    }
}
